<template>
    <div class="ChartView" ref="chart"></div>
</template>
<script lang="ts" setup>
import * as echarts from 'echarts';
import { onMounted, ref } from 'vue';
import { format } from './unit';
import Apis from '@/apis/statistics'

const chart = ref();
let ChartCanvas = null;

const emit = defineEmits(['Select']);


let testData: any = {
    UserMapping: [],
    ChartDate: [],
    series: [],
};





let ActiveIndex: number | null = null;


onMounted(async () => {
    var chartData = await Apis.list();
    testData = {
        ...format(chartData)
    };
    var option = {
        legend: {},
        xAxis: {
            type: 'category',
        },
        dataset: {
            dimensions: ['date'].concat(testData.UserMapping),
            source: testData.ChartDate
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (item: any) {
                var _array: any = [];
                for (let i = 0; i < item.length; i++) {
                    const element = item[i];
                    _array.push({
                        color: element.color,
                        name: element.seriesName,
                        value: element.data[element.seriesName]
                    });
                };
                _array.sort((a: any, b: any) => {
                    return b.value - a.value
                });
                var str = '';
                for (let i = 0; i < _array.length; i++) {
                    const element = _array[i];
                    str += `<div><i style="display:inline-block; 
width:10px; margin:0 5px 0 0; 
border-radius: 50%; 
height:10px;
background-color: ${element.color}"></i>
<span style="display:inline-block;width:50px;">${element.name}</span>
<span style="font-weight:bold;
    display:inline-block; 
    margin:0 0 0 10px; 
    text-align:right;
    width:30px;">${element.value}</span>
</div>`
                }
                return `<div>
<div style="font-weight:bold;margin:0 0 5px 0;">${item[0].value.title}</div>
    ${str}
</div>`
            }
        },
        yAxis: { type: 'value' },
        series: testData.series,
    };

    ChartCanvas = echarts.init(chart.value);
    ChartCanvas.setOption(option);
    ChartCanvas.on('highlight', (item: any) => {
        ActiveIndex = item.batch[0].dataIndex;
    });
    ChartCanvas.on('downplay', (item: any) => {
        ActiveIndex = null;
    });
    ChartCanvas.getZr().on('click', (item: any) => {
        if (ActiveIndex !== null) {
            emit('Select', testData.ChartDate[ActiveIndex])
        }
    });
})


</script>
<style lang="less" scoped>
.ChartView {
    width: 100%;
    height: calc(100vh - 200px);
    min-height: 400px;
}
</style>